#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
import requests
import os,re,IPy,time

def CDNlist(ipC):
    Default=False
    CDN = open('CDN_IPlist.txt').read().split('\n')
    for x in CDN:
        CDN_ip=IPy.IP(x)
        boolIP=(ipC in CDN_ip)
        Default=(Default or boolIP)
    return Default

def dnsR(domian):
    ns=os.popen('nslookup % s ' % domian).read()
    if ns.find('Name:') == -1:
        return []
    else:
        ns=ns[ns.find('Name:'):]
        ip = re.findall('\d+\.\d+\.\d+\.\d+', ns)
        return ip

def li(li_URL):
    HEAD={  'X-Client-Version': '3.2.5',
            'X-Channel-Code': 'official',
            'X-Client-Agent': 'samsung_SM-G9250_6.0.1',
            'X-Platform-Version': '6.0.1',
            'X-Client-Hash': '021e330ca5f14c8f8e6e7010ccf3195c',
            'X-Platform-Type': '2',
            'X-Client-ID': '359654060840700',
            'X-Serial-Num': '1502873477',
            'Host': 'app.pearvideo.com',
            'Connection': 'Keep-Alive',
            'Accept-Encoding': 'gzip',
            'User-Agent': 'okhttp/3.2.0',
            'Pragma': 'no-cache','Content-Length': '0'
        }
    try:
        r = requests.get(url=li_URL,headers=HEAD)
        domain = r.json()["dataList"][0]["contList"][0]["videos"][0]["url"][7:].split("/")[0]
        video=r.json()["dataList"][0]["contList"][0]["videos"][0]["url"]
        return domain,video
    except:
        return "打开失败","打开失败"


def main(url):
    liDomain,video=li(url)
    liIP=dnsR(liDomain)
    #print(liDomain,liIP)
    if len(liIP) == 0:
        flag = "无解析结果"
    else:
        if CDNlist(liIP[0]):
            # print(miaopai_ip)
            flag = '网内'
        else:
            flag = '出网'
    return (video,flag, "<br>".join(liIP))


if __name__ == '__main__':
    url = 'http://app.pearvideo.com/clt/jsp/v3/getVodConts.jsp?isHome=1&channelCode=&start=30'
    for i in range(10):
        t=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        res = main(url)
        print('%s\t%s\t%s\n' % res)
        fLog=open('/var/www/html/short_video/%sShortVideoLog.txt'% time.strftime("%Y-%m-%d", time.localtime()),'a' )
        fLog.write(t+'\t梨视频\t%s\t%s\t%s\n' % res)
        fLog.close()